package org.robot.scm.platform.wxrobot.processor;

import com.google.common.collect.Lists;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.LocalCacheHelper;
import org.robot.scm.platform.wxrobot.AbstractRobotProcessor;
import org.robot.scm.pojos.TargetNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.config.base.BasePlatform;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.VideoBaseNotify;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.JsonHelper;
import org.robot.scm.utils.NetImageTool;
import org.robot.scm.utils.StreamUtils;

/**
 * @Author : Awn create on 2024/4/22 15:52
 */
@Slf4j
public class VideoRobotProcessor extends AbstractRobotProcessor {

    private static final String TAG = VideoRobotProcessor.class.getSimpleName();

    @Override
    public List<String> getKeywords(BaseConfig config) {
        return config.get().getPlatform(PlatformEnum.VIDEO).getKeywords();
    }

    @Override
    protected List<TargetNotify> process(BaseConfig config, String sendTo, String msg) {
        List<String> urlTextList = JsonHelper.toList(LocalCacheHelper.get(TAG));
        if (CollectionUtils.isEmpty(urlTextList)) {
            BasePlatform currentPlatform = config.get().getPlatform(PlatformEnum.VIDEO);
            urlTextList.addAll(this.loadAndCache(currentPlatform.getNoticeSrc()));
        }
        Collections.shuffle(urlTextList);
        String videoUrl = urlTextList.get(0);
        File saveFile = new File(String.format("assets/videos/%s.mp4", Math.abs(videoUrl.hashCode())));
        if (!saveFile.exists()) {
            if (!NetImageTool.download(videoUrl, saveFile.getAbsolutePath())) {
                return Lists.newArrayList();
            }
        }
        VideoBaseNotify notice = VideoBaseNotify.builder()
                .url(saveFile.getAbsolutePath())
                .createHour(DateTool.format(new Date(), DateTool.PATTERN_6))
                .build();
        List<String> filter = StreamUtils.filter(config.get().getRobots(PlatformEnum.VIDEO), e -> StringUtils.equals(e, sendTo));
        return StreamUtils.convertAndDistinct(filter, e -> notice.robotToNotifyBean(e, config));
    }


    @SneakyThrows
    private List<String> loadAndCache(String noticeSrc) {
        String jsonConfig = FileUtils.readFileToString(new File(noticeSrc), StandardCharsets.UTF_8.name());
        List<String> imageUrls = JsonHelper.toList(jsonConfig);
        LocalCacheHelper.put(TAG, JsonHelper.toJSONString(imageUrls));
        return imageUrls;
    }
}
